<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="1640">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="检验单号" prop="no">
               <el-input disabled v-model="formData.no" placeholder="保存时自动生成"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="检验时间" prop="checkTime">
            <el-date-picker
              v-model="formData.checkTime"
              type="date"
              value-format="x"
              placeholder="选择检验时间"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>

               <el-col :span="8">
          <el-form-item label="检验员" prop="userId">
            <CascaderUser v-model="formData.userId" placeholder="请选择检验员" clearable class="!w-100%"/>
          </el-form-item>
        </el-col>
        
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="类型" prop="type">
            <el-checkbox-group v-model="typeSelection" class="flex flex-wrap gap-12px">
              <el-checkbox v-for="item in typeOptions" :key="item" :label="item">
                {{ item }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="检验依据" prop="basis">
            <el-checkbox-group v-model="basisSelection" class="flex flex-wrap gap-12px">
              <el-checkbox v-for="item in basisOptions" :key="item" :label="item">
                {{ item }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="外观" prop="surface">
            <el-checkbox-group v-model="surfaceSelection" class="flex flex-wrap gap-12px">
              <el-checkbox v-for="item in surfaceOptions" :key="item" :label="item">
                {{ item }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="结果" prop="result">
               <el-select
          v-model="formData.result"
          placeholder="请选择结果"
          clearable
         
        >
          <el-option label="合格" value="合格" />
          <el-option label="不合格" value="不合格" />
        </el-select>
          </el-form-item>
        </el-col>
           <el-col :span="6">
          <el-form-item label="是否量产" prop="isPlan">
             <el-select
          v-model="formData.isPlan"
          placeholder="请选择是否量产"
          clearable
        >
          <el-option label="是" value="是" />
          <el-option label="否" value="否" />
        </el-select>
          </el-form-item>
        </el-col>
         <el-col :span="6">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="formData.remark"  placeholder="请输入备注" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="附件 URL" prop="fileUrl">
              <upload-file v-model="formData.fileUrl" :isShowTip="false"/>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 首件检验注意事项 -->
      <el-row :gutter="20" style="margin-bottom: 20px">
        <el-col :span="24">
          <el-collapse v-model="activeNames" style="border: 1px solid #409eff; border-radius: 4px">
            <el-collapse-item name="1">
              <template #title>
                <div style="color: #409eff; font-weight: bold; font-size: 14px">
                  <el-icon style="margin-right: 5px"><InfoFilled /></el-icon>
                  首件检验注意事项（请仔细阅读）
                </div>
              </template>

              <!-- 基本规定 -->
              <div style="margin-bottom: 15px">
                <h4 style="color: #303133; margin: 10px 0">一、基本规定</h4>
                <div style="padding-left: 20px; line-height: 1.8">
                  <p><strong>1. 检验范围：</strong>所有项目均需连续检验最少5件</p>
                  <p><strong>2. 统计要求：</strong>根据质量统计的良品项目进行统计验证</p>
                </div>
              </div>

              <!-- 检验内容 -->
              <div style="margin-bottom: 15px; background: #f0f9ff; padding: 10px; border-radius: 4px">
                <h4 style="color: #303133; margin: 10px 0">二、检验内容</h4>
                <div style="padding-left: 20px; line-height: 1.8">
                  <p><strong>1. 产品部件检查：</strong>由成型部门对应首件，由送检部门对各个件符合首件标准并选知IPQC检验品，检验判定合格后生产</p>
                  <p><strong>2. 验算判定和批次：</strong>检验合格后才可推进完整的出货检验工位</p>
                  <p><strong>3. 首样见证：</strong>选择回收记录单，并提向巡验记录是一起留存于线检验查上位</p>
                </div>
              </div>

              <!-- 造型包检 -->
              <div style="background: #fff3e0; padding: 10px; border-radius: 4px; border-left: 4px solid #ff9800">
                <h4 style="color: #303133; margin: 10px 0">三、造型包检</h4>
                <div style="padding-left: 20px; line-height: 1.8">
                  <p>造用包因：产品部开机、开线、修模、变更工艺/参数、变更材料等均需要进行首件检验。</p>
                </div>
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-col>
      </el-row>

      <el-form-item label="检验数据" prop="checkData">
        <el-form ref="checkDataFormRef" :model="{checkData}" label-width="0px" :inline-message="true">
          <el-table :data="checkData" border size="small" >
            <el-table-column label="序号" type="index" align="center" width="60" />
            <el-table-column label="产品名称" min-width="300">
              <template #default="{ row, $index }">
                <el-form-item :prop="`checkData.${$index}.productName`" :rules="checkDataRules.productName" class="mb-0px!">
                  <ErpSelectRemoteProduct  v-model="row.productName" placeholder="请输入产品名称" />
                </el-form-item>
              </template>
            </el-table-column>
          <el-table-column label="原料" min-width="120">
            <template #default="{ row }">
              <el-input v-model="row.material" placeholder="请输入原料" />
            </template>
          </el-table-column>
          <el-table-column label="机器" min-width="120">
            <template #default="{ row }">
              <ErpSelectMachine v-model="row.machine" placeholder="请选择机器" />
            </template>
          </el-table-column>
          <el-table-column label="模具" min-width="120">
            <template #default="{ row }">
              <ErpSelectMould v-model="row.mould" placeholder="请选择模具" />
            </template>
          </el-table-column>
          <el-table-column label="尺寸" min-width="120">
            <template #default="{ row }">
              <el-input v-model="row.size" placeholder="请输入尺寸" />
            </template>
          </el-table-column>
          <el-table-column label="检验数量" align="center" width="80">
            <template #default="{ row }">
              <el-input-number
                v-model="row.quantity"
                :min="0"
                :controls="false"
                style="width: 100%"
              />
            </template>
          </el-table-column>
          <el-table-column label="判定结果" align="center" width="150">
            <template #default="{ row }">
              <el-select v-model="row.judgement" placeholder="请选择判定结果">
                <el-option label="合格" value="合格" />
                <el-option label="不合格" value="不合格" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="备注" min-width="160">
            <template #default="{ row }">
              <el-input
                v-model="row.remark"
                type="textarea"
                placeholder="请输入备注"
                :autosize="{ minRows: 1, maxRows: 3 }"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="90" fixed="right">
            <template #default="{ $index }">
              <el-button
                link
                type="danger"
                @click="removeCheckDataRow($index)"
                :icon="Delete"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
          </el-table>
          <el-button
            type="primary"
            plain
            style="margin-top: 10px; width: 100%"
            :icon="Plus"
            @click="addCheckDataRow"
          >
            新增检验数据
          </el-button>
        </el-form>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确认</el-button>
      <el-button @click="dialogVisible = false">取消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { Plus, Delete, InfoFilled } from '@element-plus/icons-vue'
import { CheckInitApi, CheckInit } from '@/api/erp/check/init'
import CascaderUser from '@/components/CascaderUser/CascaderUser.vue'
import ErpSelectRemoteProduct from '../../product/product/components/ErpSelectRemoteProduct.vue'
import ErpSelectMachine from '../../basic/machine/components/ErpSelectMachine.vue'
import ErpSelectMould from '../../basic/mould/components/ErpSelectMould.vue'

defineOptions({ name: 'CheckInitForm' })

const { t } = useI18n()
const message = useMessage()

const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref('')
const formRef = ref()
const checkDataFormRef = ref()
const activeNames = ref(['1']) // 折叠面板默认展开

const formData = ref({
  id: undefined,
  no: undefined,
  checkTime: undefined,
  checkData: undefined,
  type: undefined,
  basis: undefined,
  surface: undefined,
  result: undefined,
  isPlan: undefined,
  userId: undefined,
  status: undefined,
  remark: undefined,
  fileUrl: undefined
})

const typeOptions = [
  '开机首检',
  '修模首件',
  '转产首件',
  '生产参数变更',
  '材料变更',
  '更换颜色'
]

const basisOptions = ['工程图纸', '标准样件', '制程检验标准', '产品标准', '其他']

const surfaceOptions = [
  '少孔',
  '开裂',
  '变形',
  '起皱、堆料',
  '孔毛刺',
  '飞边毛刺',
  '划伤',
  '压痕',
  '拉痕',
  '缺料',
  '色差'
]

const normalizeSelection = (values: string[]): string[] => {
  return Array.from(
    new Set(values.map((item) => item.trim()).filter((item) => item.length > 0))
  )
}

const toSelectionArray = (value: unknown): string[] => {
  if (Array.isArray(value)) {
    return normalizeSelection(value as string[])
  }
  if (value === null || value === undefined) {
    return []
  }
  return normalizeSelection(String(value).split(','))
}

const toSelectionValue = (values: string[]): string | undefined => {
  const normalized = normalizeSelection(values)
  return normalized.length > 0 ? normalized.join(',') : undefined
}

const typeSelection = computed<string[]>({
  get: () => toSelectionArray(formData.value.type),
  set: (value) => {
    formData.value.type = toSelectionValue(value)
  }
})

const basisSelection = computed<string[]>({
  get: () => toSelectionArray(formData.value.basis),
  set: (value) => {
    formData.value.basis = toSelectionValue(value)
  }
})

const surfaceSelection = computed<string[]>({
  get: () => toSelectionArray(formData.value.surface),
  set: (value) => {
    formData.value.surface = toSelectionValue(value)
  }
})

interface CheckDataItem {
  productName: string
  material: string
  machine: string
  mould: string
  size: string
  quantity: number
  judgement: string
  remark: string
}

const createEmptyCheckDataRow = (): CheckDataItem => ({
  productName: '',
  material: '',
  machine: '',
  mould: '',
  size: '',
  quantity: 0,
  judgement: '',
  remark: ''
})

const initCheckData = (): CheckDataItem[] => [createEmptyCheckDataRow()]

const checkData = ref<CheckDataItem[]>(initCheckData())

const formRules = reactive({
  nuserId: [{ required: true, message: '检验员不能为空', trigger: 'blur' }],
  checkTime: [{ required: true, message: '检验时间不能为空', trigger: 'change' }],
  result: [{ required: true, message: '结果不能为空', trigger: 'change' }],
  isPlan: [{ required: true, message: '是否量产不能为空', trigger: 'change' }]
})

const checkDataRules = reactive({
  productName: [{ required: true, message: '产品名称不能为空', trigger: 'blur' }]
})

const syncCheckDataToForm = () => {
  formData.value.checkData = JSON.stringify(checkData.value)
}

syncCheckDataToForm()

watch(
  checkData,
  () => {
    syncCheckDataToForm()
    if (formRef.value?.clearValidate) {
      formRef.value.clearValidate('checkData')
    }
  },
  { deep: true }
)

const addCheckDataRow = () => {
  checkData.value.push(createEmptyCheckDataRow())
}

const removeCheckDataRow = (index: number) => {
  if (checkData.value.length <= 1) {
    message.warning('至少保留一行检验数据')
    return
  }
  checkData.value.splice(index, 1)
}

const toNumber = (value: unknown): number => {
  const num = Number(value)
  return Number.isFinite(num) ? num : 0
}

const normalizeCheckData = (rows: unknown): CheckDataItem[] => {
  if (!Array.isArray(rows) || rows.length === 0) {
    return initCheckData()
  }
  return (rows as any[]).map((row) => ({
    productName: row?.productName ?? '',
    material: row?.material ?? '',
    machine: row?.machine ?? '',
    mould: row?.mould ?? '',
    size: row?.size ?? '',
    quantity: toNumber(row?.quantity),
    judgement: row?.judgement ?? '',
    remark: row?.remark ?? ''
  }))
}

const loadCheckData = (raw: unknown) => {
  if (!raw) {
    checkData.value = initCheckData()
    return
  }
  try {
    const parsed = typeof raw === 'string' ? JSON.parse(raw) : raw
    checkData.value = normalizeCheckData(parsed)
  } catch (error) {
    console.error('检验数据解析失败', error)
    checkData.value = initCheckData()
  }
  syncCheckDataToForm()
}

const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  if (id) {
    formLoading.value = true
    try {
      formData.value = await CheckInitApi.getCheckInit(id)
      loadCheckData(formData.value.checkData)
    } finally {
      formLoading.value = false
    }
  }
}

defineExpose({ open })

const emit = defineEmits(['success'])

const submitForm = async () => {
  await formRef.value?.validate()
  await checkDataFormRef.value?.validate()
  formLoading.value = true
  try {
    syncCheckDataToForm()
    const data = formData.value as unknown as CheckInit
    if (formType.value === 'create') {
      await CheckInitApi.createCheckInit(data)
      message.success(t('common.createSuccess'))
    } else {
      await CheckInitApi.updateCheckInit(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const resetForm = () => {
  formRef.value?.resetFields()
  formData.value = {
    id: undefined,
    no: undefined,
    checkTime: undefined,
    checkData: undefined,
    type: undefined,
    basis: undefined,
    surface: undefined,
    result: undefined,
    isPlan: undefined,
    userId: undefined,
    status: undefined,
    remark: undefined,
    fileUrl: undefined
  }
  checkData.value = initCheckData()
  syncCheckDataToForm()
  formRef.value?.clearValidate()
}
</script>
